import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dartz/dartz.dart';

import 'api_result.dart';
import '../../config/local_config_manager.dart';
import '../../config/server_config.dart';

/// HTTP客户端配置
class HttpClientConfig {
  const HttpClientConfig({
    this.baseUrl = '', // 直接从LocalConfigManager获取
    this.connectTimeout = const Duration(seconds: 10),
    this.receiveTimeout = const Duration(seconds: 30),
    this.sendTimeout = const Duration(seconds: 30),
  });

  final String baseUrl;
  final Duration connectTimeout;
  final Duration receiveTimeout;
  final Duration sendTimeout;

  /// 直接从LocalConfigManager创建HttpClientConfig（优化后的版本）
  factory HttpClientConfig.fromLocalConfig() {
    final localConfig = LocalConfigManager.instance;
    
    // 直接从持久化配置中获取baseUrl，使用ServerConfig作为默认值
    String baseUrl = localConfig.getValue<String>('baseUrl', ServerConfig.baseUrl) ?? ServerConfig.baseUrl;
    
    // 构建完整的API URL
    String apiBaseUrl = baseUrl;
    if (!apiBaseUrl.endsWith('/api')) {
      if (!apiBaseUrl.endsWith('/')) {
        apiBaseUrl += '/api';
      } else {
        apiBaseUrl += 'api';
      }
    }

    // 获取超时配置，使用ServerConfig作为默认值
    final timeoutMs = localConfig.getValue<int>('timeout', ServerConfig.timeout) ?? ServerConfig.timeout;
    final timeout = Duration(milliseconds: timeoutMs);

    // 调试日志：输出当前使用的配置
    print('🌐 HttpClientConfig.fromLocalConfig: baseUrl=${apiBaseUrl} (从LocalConfigManager获取，默认值来自ServerConfig)');

    return HttpClientConfig(
      baseUrl: apiBaseUrl,
      connectTimeout: timeout,
      receiveTimeout: timeout,
      sendTimeout: timeout,
    );
  }

  /// 兼容性方法，重定向到新的fromLocalConfig
  @Deprecated('使用 fromLocalConfig() 代替，直接从持久化配置管理中获取')
  factory HttpClientConfig.fromAppConfig() {
    print('⚠️ 使用了已废弃的fromAppConfig，正在重定向到fromLocalConfig');
    return HttpClientConfig.fromLocalConfig();
  }

  /// 创建一个新的配置实例，用于更新
  HttpClientConfig copyWith({
    String? baseUrl,
    Duration? connectTimeout,
    Duration? receiveTimeout,
    Duration? sendTimeout,
  }) {
    return HttpClientConfig(
      baseUrl: baseUrl ?? this.baseUrl,
      connectTimeout: connectTimeout ?? this.connectTimeout,
      receiveTimeout: receiveTimeout ?? this.receiveTimeout,
      sendTimeout: sendTimeout ?? this.sendTimeout,
    );
  }
}

/// 现代化的HTTP客户端
class HttpClient {
  HttpClient(this._config) {
    _dio = Dio(BaseOptions(
      baseUrl: _config.baseUrl,
      connectTimeout: _config.connectTimeout,
      receiveTimeout: _config.receiveTimeout,
      sendTimeout: _config.sendTimeout,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
    ));

    // 添加拦截器
    _dio.interceptors.addAll([
      _AuthInterceptor(),
      _LoggingInterceptor(),
      _ErrorInterceptor(),
    ]);
  }

  final HttpClientConfig _config;
  late final Dio _dio;
  
  /// 获取baseUrl（用于调试和错误信息）
  String get baseUrl => _config.baseUrl;

  /// GET请求
  Future<ApiResult<T>> get<T>(
    String path, {
    Map<String, dynamic>? queryParameters,
    T Function(Map<String, dynamic>)? fromJson,
  }) async {
    try {
      final response = await _dio.get<Map<String, dynamic>>(
        path,
        queryParameters: queryParameters,
      );
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }

  /// POST请求
  Future<ApiResult<T>> post<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    T Function(Map<String, dynamic>)? fromJson,
  }) async {
    try {
      final response = await _dio.post<Map<String, dynamic>>(
        path,
        data: data,
        queryParameters: queryParameters,
      );
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }

  /// PUT请求
  Future<ApiResult<T>> put<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    T Function(Map<String, dynamic>)? fromJson,
  }) async {
    try {
      final response = await _dio.put<Map<String, dynamic>>(
        path,
        data: data,
        queryParameters: queryParameters,
      );
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }

  /// DELETE请求
  Future<ApiResult<T>> delete<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    T Function(Map<String, dynamic>)? fromJson,
  }) async {
    try {
      final response = await _dio.delete<Map<String, dynamic>>(
        path,
        data: data,
        queryParameters: queryParameters,
      );
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }

  /// PATCH请求
  Future<ApiResult<T>> patch<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    T Function(Map<String, dynamic>)? fromJson,
  }) async {
    try {
      final response = await _dio.patch<Map<String, dynamic>>(
        path,
        data: data,
        queryParameters: queryParameters,
      );
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }

  /// 处理响应
  ApiResult<T> _handleResponse<T>(
    Response<Map<String, dynamic>> response,
    T Function(Map<String, dynamic>)? fromJson,
  ) {
    final data = response.data;
    if (data == null) {
      return const Left(ServerFailure('响应数据为空'));
    }

    final apiResponse = ApiResponse<dynamic>.fromJson(data, (json) => json);
    
    if (!apiResponse.success) {
      return Left(ServerFailure(
        apiResponse.message,
        apiResponse.code,
      ));
    }

    if (fromJson != null && apiResponse.data != null) {
      try {
        final result = fromJson(apiResponse.data as Map<String, dynamic>);
        return Right(result);
      } catch (e) {
        return Left(ParseFailure('数据解析失败: $e'));
      }
    }

    return Right(apiResponse.data as T);
  }

  /// 处理错误
  ApiResult<T> _handleError<T>(dynamic error) {
    if (error is DioException) {
      switch (error.type) {
        case DioExceptionType.connectionTimeout:
        case DioExceptionType.sendTimeout:
        case DioExceptionType.receiveTimeout:
          return const Left(NetworkFailure('网络超时'));
        case DioExceptionType.badResponse:
          final statusCode = error.response?.statusCode;
          if (statusCode == 401) {
            return const Left(AuthFailure('认证失败'));
          } else if (statusCode != null && statusCode >= 500) {
            return const Left(ServerFailure('服务器错误'));
          }
          return Left(ServerFailure('请求失败: ${error.message}'));
        case DioExceptionType.cancel:
          return const Left(NetworkFailure('请求已取消'));
        case DioExceptionType.connectionError:
          return const Left(NetworkFailure('网络连接失败'));
        default:
          return Left(NetworkFailure('网络错误: ${error.message}'));
      }
    }
    return Left(NetworkFailure('未知错误: $error'));
  }
}

/// 认证拦截器
class _AuthInterceptor extends Interceptor {
  // 🔑 Token key必须与AuthService保持一致
  static const String _tokenKey = 'auth_token';
  static const String _refreshTokenKey = 'refresh_token';

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final token = prefs.getString(_tokenKey); // 修复：使用正确的key
      if (token != null && token.isNotEmpty) {
        options.headers['Authorization'] = 'Bearer $token';
        // print('🔑 [AuthInterceptor] 已添加Authorization头: Bearer ${token.substring(0, 20)}...');
      }
    } catch (e) {
      // 忽略错误，继续请求
      print('⚠️ [AuthInterceptor] 获取token失败: $e');
    }
    handler.next(options);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    if (err.response?.statusCode == 401) {
      // 尝试刷新Token
      try {
        final prefs = await SharedPreferences.getInstance();
        final refreshToken = prefs.getString(_refreshTokenKey);
        if (refreshToken != null) {
          // TODO: 实现Token刷新逻辑
        }
      } catch (e) {
        // 刷新失败，清除Token
        final prefs = await SharedPreferences.getInstance();
        await prefs.remove(_tokenKey);
        await prefs.remove(_refreshTokenKey);
      }
    }
    handler.next(err);
  }
}

/// 日志拦截器
class _LoggingInterceptor extends Interceptor {
  final Logger _logger = Logger();

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    _logger.d('🚀 ${options.method} ${options.uri}');
    if (options.data != null) {
      _logger.d('📤 Request Data: ${options.data}');
    }
    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    _logger.d('✅ ${response.statusCode} ${response.requestOptions.uri}');
    _logger.d('📥 Response Data: ${response.data}');
    handler.next(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    _logger.e('❌ ${err.requestOptions.method} ${err.requestOptions.uri}');
    _logger.e('Error: ${err.message}');
    if (err.response != null) {
      _logger.e('Response: ${err.response?.data}');
    }
    handler.next(err);
  }
}

/// 错误拦截器
class _ErrorInterceptor extends Interceptor {
  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    // 可以在这里添加全局错误处理逻辑
    // 例如：显示通用错误提示、上报错误等
    handler.next(err);
  }
}

/// 配置感知的HTTP客户端配置Provider（优化版本）
final httpClientConfigProvider = Provider<HttpClientConfig>((ref) {
  return HttpClientConfig.fromLocalConfig();
});

/// HTTP客户端Provider（已弃用，使用reactiveHttpClientProvider）
@Deprecated('使用 reactiveHttpClientProvider 代替，它支持配置热更新')
final httpClientProvider = Provider<HttpClient>((ref) {
  print('⚠️ 使用了已废弃的httpClientProvider，请使用reactiveHttpClientProvider');
  final config = ref.watch(httpClientConfigProvider);
  return HttpClient(config);
});

/// 配置重新加载通知Provider
final configReloadNotifierProvider = StateNotifierProvider<ConfigReloadNotifier, int>((ref) {
  return ConfigReloadNotifier();
});

/// 配置重新加载通知器
class ConfigReloadNotifier extends StateNotifier<int> {
  ConfigReloadNotifier() : super(0);

  /// 通知配置已重新加载
  void notifyConfigReloaded() {
    state = state + 1;
  }
}

/// 本地配置变化通知Provider
final localConfigChangeNotifierProvider = StateNotifierProvider<LocalConfigChangeNotifier, int>((ref) {
  return LocalConfigChangeNotifier();
});

/// 本地配置变化通知器
class LocalConfigChangeNotifier extends StateNotifier<int> {
  LocalConfigChangeNotifier() : super(0) {
    // 监听LocalConfigManager的变化
    LocalConfigManager.instance.addListener(_onConfigChanged);
  }

  void _onConfigChanged() {
    state = state + 1;
    print('🔄 LocalConfigChangeNotifier: 配置已变更，触发重新构建');
  }

  @override
  void dispose() {
    LocalConfigManager.instance.removeListener(_onConfigChanged);
    super.dispose();
  }
}

/// 响应式HTTP客户端配置Provider - 优化版本，直接读取LocalConfigManager并监听变化
final reactiveHttpClientConfigProvider = Provider<HttpClientConfig>((ref) {
  // 监听配置变化
  ref.watch(localConfigChangeNotifierProvider);
  
  print('🔄 reactiveHttpClientConfigProvider: 重新创建配置（响应配置变更）');
  return HttpClientConfig.fromLocalConfig();
});

/// 响应式HTTP客户端Provider - 配置变化时自动更新
final reactiveHttpClientProvider = Provider<HttpClient>((ref) {
  final config = ref.watch(reactiveHttpClientConfigProvider);
  return HttpClient(config);
});

/// HTTP客户端配置集成器 - 简化版本，直接使用LocalConfigManager
class HttpClientConfigIntegration {
  static ProviderContainer? _container;
  static bool _initialized = false;

  /// 初始化集成（简化版本）
  static void initialize(ProviderContainer container) {
    if (_initialized) return;
    
    _container = container;
    
    // 确保LocalConfigManager已初始化，配置变化会自动通过LocalConfigChangeNotifier传播
    _initialized = true;
    print('✅ HttpClientConfigIntegration: 简化版本初始化完成');
  }

  /// 清理集成
  static void dispose() {
    _container = null;
    _initialized = false;
    print('🧹 HttpClientConfigIntegration: 已清理');
  }

  /// 强制刷新HTTP客户端配置（通过LocalConfigManager的监听器自动触发）
  static void forceRefresh() {
    if (_container != null && _initialized) {
      print('🔄 HttpClient: 强制刷新配置（通过LocalConfigChangeNotifier）');
      // 配置变化会自动通过LocalConfigChangeNotifier传播，无需手动触发
      _container!.read(localConfigChangeNotifierProvider.notifier)._onConfigChanged();
    }
  }
}
